/**
 * Created by shidaiapp on 2017/9/29.
 */
import ApiBase from "../../../../api/moudles/ApiBase"

function changeModelLoading(self, tiyData) {
  tiyData.tStatus.modalFolder.isLoading = false;
  tiyData.tStatus.modalDelete.isLoading = false;
  self.$nextTick(function () {
    tiyData.tStatus.modalFolder.isLoading = true;
    tiyData.tStatus.modalDelete.isLoading = true;
  });

}
/**
 * 初始化
 * @param self
 * @param tiyData
 */
export const imageInit = (self, tiyData, showChooseSingle, isSingle, folderType) => {
  //resetForm(self, tiyData);
  tiyData.tData.folderList.length = 0;
  tiyData.tData.folderList.length = 0;
  tiyData.tPage.total = 1;
  tiyData.tPage.startIndex = 0;
  tiyData.tPage.stepNumber = 20;
  tiyData.tPage.currentPage = 1;
  tiyData.tParams.folderName = '';
  tiyData.tParams.orderBy = '';
  tiyData.tParams.folderType = folderType;//目录的类型，只限一级目录 1: 产品 2：模特 3：活动 4:标签 5：分类
  tiyData.tStatus.breadcrumbList = [];
  tiyData.tStatus.showChooseSingle = showChooseSingle;
  tiyData.tStatus.isSingle = isSingle;
};


/**
 * 新件文件夹
 * @param self
 * @param tiyData
 * @returns {Array}
 */
export const webImageAdd = (self, tiyData, name) => {
  tiyData.tStatus.modalFolder.isLoading = true;
  self.$refs[name].validate((valid) => {
    if (valid) {
      Loading(self, tiyData);
      self.$apiImage.createFolder({
        folderName: tiyData.tParams.folder.name,
        folderId: tiyData.tParams.folder.parentId,//父id
      }).then(function (response) {
        noLoading(self, tiyData);
        changeModelLoading(self, tiyData);
        if (response.success) {
          tiyData.tStatus.modalFolder.isShow = false;
          webFolderListByParentId(self, tiyData, null);
        } else {
          self.$Message.error(response.errorMessage);
        }
      });
    } else {
      changeModelLoading(self, tiyData);
    }
  });
};
/**
 * 删除对象
 * @param self
 * @param tiyData
 * @returns {Array}
 */
export const webImageDelete = (self, tiyData) => {
  Loading(self, tiyData);
  tiyData.tStatus.modalDelete.isLoading = true;
  let ids = '';
  tiyData.tStatus.modalDelete.folder.objectIds.forEach(function (item) {
    ids = ids + item + ',';
  });
  self.$apiImage.deleteFolderOrImages({
    objectIds: ids,
    type: tiyData.tStatus.modalDelete.folder.type
  }).then(function (response) {
    noLoading(self, tiyData);
    changeModelLoading(self, tiyData);
    if (response.success) {
      tiyData.tStatus.modalDelete.isShow = false;
      webFolderListByParentId(self, tiyData, null);
    } else {
      self.$Message.error(response.errorMessage);
      tiyData.tStatus.modalDelete.isShow = false;
    }
  });
};

/**
 * 从服务器请求列表
 * @param self
 * @param tiyData
 * @returns {Array}
 */
export const webImageList = (self, tiyData) => {
  Loading(self, tiyData);
  self.$apiImage.getItemFolderList({
    folderName: tiyData.tParams.folderList.folderName,
    type: tiyData.tParams.folderType,
  }).then(function (response) {
    if (response.success) {
      noLoading(self, tiyData);
      tiyData.tData.folderTreeData.length = 0;
      tiyData.tData.folderList.length = 0;

      //面包屑导航
      let folderItem = response.result.folder;
      tiyData.tParams.uploadParam.folderId = folderItem.id;
      let requestMsg = ApiBase.createRequestMsg(tiyData.tParams.uploadParam);

      tiyData.tParams.folder.parentId = folderItem.id;
      tiyData.tParams.folderList.foderId = folderItem.id;
      tiyData.tParams.folderList.level = folderItem.level + 1;
      tiyData.tParams.uploadFolderParam = {requestMsg: JSON.stringify(requestMsg)}
      tiyData.tStatus.breadcrumbList.length = 0;
      tiyData.tStatus.breadcrumbList.push(folderItem);

      //目录和文件列表
      let folderPage = response.result.page;
      tiyData.tPage.currentPage = folderPage.pageNum;
      tiyData.tPage.total = folderPage.total;
      folderPage.list.forEach(
        function (item) {
          let treeDataItem = {
            title: item.name,
            name: item.name,
            expand: false,
            id: item.id,
            level: item.level,
            parentId: item.parentId,
            parentName: item.parentName,
            render: (h, {root, node, data}) => {
              // return <span style=" display: 'inline-block';width: '100%'"><span><Icon type="ios-folder-outline"></Icon>data.title</span></span>
              return h('span', {
                style: {
                  display: 'inline-block',
                  float: 'left',
                  marginLeft: '50px'
                },
                on: {
                  click: () => {
                    selectedForTree(self,tiyData,data);
                  }
                },
              }, [
                h('span',
                  [
                    h('Icon', {
                      props: {
                        type: data.expand ? 'ios-folder' : 'ios-folder-outline',
                        size: 13
                      },
                      style: {
                        marginRight: '8px'
                      }
                    }),
                    h('span', data.title)
                  ]),
              ]);
            },
          };
          tiyData.tData.folderList.push(item);
          tiyData.tData.folderTreeData.push(treeDataItem);
          // tiyData.tStatus.breadcrumbList.push(item);
        }
      );
      if (0 === tiyData.tData.folderTreeData.length) {
        self.$Message.error("查询没有结果");
      }
      //初始只有一个文件夹，直接打开进入
      // if(1 == tiyData.tData.folderList.length) {
      //   selectedForTree(self,tiyData,tiyData.tData.folderList[0]);
      // }
    } else {
      self.$Message.error(response.errorMessage);
    }
  });
};

/**
 * 从服务器请求列表
 * @param self
 * @param tiyData
 * @returns {Array}
 */
export const webFolderListByParentId = (self, tiyData, folderItem) => {
  Loading(self, tiyData);
  if (null != folderItem) {
    tiyData.tParams.uploadParam.folderId = folderItem.id;
    let requestMsg = ApiBase.createRequestMsg(tiyData.tParams.uploadParam);
    tiyData.tParams.folder.parentId = folderItem.id;
    tiyData.tParams.uploadFolderParam = {requestMsg: JSON.stringify(requestMsg)};
    //文件级别导航栏
    if (1 === folderItem.level) {//level 从1开始 假如点击的是第一级的 初化化breadcrumb
      tiyData.tStatus.breadcrumbList.length = 0;
      tiyData.tStatus.breadcrumbList.push(folderItem);
    } else {
      if (tiyData.tStatus.breadcrumbList.length > 0) {
        //导航栏最大的level
        let barMaxLevel = tiyData.tStatus.breadcrumbList[tiyData.tStatus.breadcrumbList.length - 1].level;
        if (folderItem.level > barMaxLevel) {
          tiyData.tStatus.breadcrumbList.push(folderItem);
        } else {
          tiyData.tStatus.breadcrumbList.forEach(function (item, index) {
            if (item.level === folderItem.level) {
              tiyData.tStatus.breadcrumbList.splice(index, tiyData.tStatus.breadcrumbList.length - index, folderItem);
            }
          });
        }
      } else {
        tiyData.tStatus.breadcrumbList.push(folderItem);
      }
    }
  }
  self.$apiImage.getFolderListByParentId({
    "pageSize": tiyData.tPage.stepNumber,
    "pageNum": tiyData.tPage.currentPage,
    "foderId": tiyData.tParams.folderList.foderId,
    "keyCode": tiyData.tParams.folderList.keyCode,
    "folderType": tiyData.tParams.folderList.folderType,
    "productCode": tiyData.tParams.folderList.productCode,
    "folderName": tiyData.tParams.folderList.folderName,
    "orderList": tiyData.tParams.folderList.orderList,
    // "level": tiyData.tParams.folderList.level,
  }).then(function (response) {
    if (response.success) {
      noLoading(self, tiyData);
      let folderTreeChilder = [];
      let folderPage = response.result;
      tiyData.tData.folderList.length = 0;
      tiyData.tPage.total = folderPage.total;
      tiyData.tPage.stepNumber = folderPage.pageSize;
      folderPage.list.forEach(
        function (item) {
          if ('' === item.suffix) {
            let treeDataItem = {
              title: item.name,
              name: item.name,
              expand: false,
              id: item.id,
              level: item.level,
              parentId: item.parentId,
              parentName: item.parentName,
              render: (h, {root, node, data}) => {
                // return <span style=" display: 'inline-block';width: '100%'"><span><Icon type="ios-folder-outline"></Icon>data.title</span></span>
                return h('span', {
                  style: {
                    display: 'inline-block',
                    float: 'left',
                    marginLeft: '50px'

                  }, on: {
                    click: () => {
                      selectedForTree(self,tiyData,data);
                    }
                  },
                }, [
                  h('span',
                    [
                      h('Icon', {
                        props: {
                          type: data.expand ? 'ios-folder' : 'ios-folder-outline',
                          size: 13
                        },
                        style: {
                          marginRight: '8px'
                        }
                      }),
                      h('span', data.title)
                    ]),
                ]);
              },
            };
            folderTreeChilder.push(treeDataItem);

          }

          tiyData.tData.folderList.push(item);
        }
      );
      let nowTreeData;
      tiyData.tData.folderTreeData.forEach(function (itemTree) {
        itemTree.expand = false;
      });
      //文件tree
      tiyData.tStatus.breadcrumbList.forEach(function (item, index) {
        if (index === 0) {
          nowTreeData = tiyData.tData.folderTreeData.filter(folderTree => folderTree.level === item.level && folderTree.id === item.id)[0];
          tiyData.tData.folderTreeData.forEach(function (itemTree) {
            if (itemTree.level === item.level && itemTree.id !== item.id) {
              itemTree.children = [];
              itemTree.expand = false;
            } else {
              itemTree.expand = true;
            }
          });
        } else {
          nowTreeData.children.forEach(function (itemTree) {
            if (itemTree.level === item.level && itemTree.id !== item.id) {
              itemTree.children = [];
              itemTree.expand = false;
            } else {
              itemTree.expand = true;
            }
          });
          nowTreeData = nowTreeData.children.filter(folderTree => folderTree.level === item.level && folderTree.id === item.id)[0];
        }
      });
      if(nowTreeData != undefined) {
        nowTreeData.children = folderTreeChilder;
        nowTreeData.expand = true;
      }
    } else {
      self.$Message.error(response.errorMessage);
    }
  });
};

function Loading(self, tiyData) {
  tiyData.tStatus.spinLoading = true;
}
function noLoading(self, tiyData) {
  tiyData.tStatus.spinLoading = false;
}

function selectedForTree(slef, tiyData, folderItem) {
  tiyData.tPage.currentPage = 1;
  tiyData.tParams.folderList.foderId = folderItem.id;
  tiyData.tParams.folderList.level = folderItem.level + 1;
  webFolderListByParentId(slef, tiyData, folderItem);
}
function ShowTheObject(obj, tag) {
  if (null == tag) {
    tag = '';
  }
  var des = "";
  for (var name in obj) {
    des += name + ":" + obj[name] + ";";
  }
}

